<script setup lang="ts">
import { getProductListApi, deleteProductApi } from '@/api/product'
import { onMounted, ref, computed } from 'vue'
import { formatTime } from '@/utils/formatTime'
import {
    InfoFilled,
    Delete,
    Edit,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import router from '@/router';

interface ProductType {
    [key: string]: any
    title: string
    introduction: string
    detial: string
    cover: string
    updateTime: string
}

let productInfo = ref<ProductType[]>([])
let loading = ref(true)

const search = ref('')
const filterTableData = computed(() =>

    productInfo.value.filter(
        (data) =>
            !search.value ||
            data.title.toLowerCase().includes(search.value.toLowerCase())
    )
)

const getProductList = async () => {
    const result = await getProductListApi()
    productInfo.value = result.data.data
}

const confirmDelete = async (index: number, row: ProductType) => {
    console.log(row._id);
    await deleteProductApi(row._id)
    await getProductList()
    ElMessage({
        type: 'success',
        message: '删除成功'
    })
}

const handleEdit = (row: ProductType) => {
    router.push({
        path: `/product-manage/productEdit/${row._id}`
    })
}

onMounted(async () => {
    await getProductList()
    loading.value = false
})
</script>

<template>
    <div>
        <el-table v-loading="loading" :data="filterTableData" style="width: 100%" max-height="800px" stripe>
            <el-table-column label="产品名称" prop="title" />
            <el-table-column label="简要描述" prop="introduction" width="600px"/>
            <el-table-column label="更新时间" prop="updateTime">
                <template #default="scope">
                    {{ formatTime.getTime(scope.row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column align="right">
                <template #header>
                    <el-input v-model="search" size="large" placeholder="搜索产品名称" />
                </template>
                <template #default="scope">
                    <el-button type="warning" plain :icon="Edit" circle @click="handleEdit(scope.row)" />
                    <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled"
                        icon-color="rgb(242, 111, 109)" title="确认删除?" @confirm="confirmDelete(scope.$index, scope.row)">
                        <template #reference>
                            <el-button type="danger" plain :icon="Delete" circle />
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<style lang='less' scoped></style>